package com.yirui.serialcomm.service;

import com.fazecast.jSerialComm.SerialPort;
import com.yirui.serialcomm.core.protocol.Context;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 串口与网络连接管理
 * @author Dujie
 * @create 2025/8/13
 * @since 1.0.0
 */
public class ConnectionManager {
    private Context context;
    private Map<String, Connection> pools = new ConcurrentHashMap<>();
    public ConnectionManager(Context ctx) {
        this.context = ctx;
    }

    public void addConnection(SerialPort port) {
        Connection connection = new SimpleConnection(port);
        pools.put(port.getSystemPortName(), connection);
    }

    /**
     * 开启连接串口与网络通道
     */
    public void start() {
        pools.forEach((key, c)->{
            c.startup(context);
        });

    }

    /**
     * 销毁处理
     *
     */
    public void destroy(){
        pools.forEach((key, c)->{
            c.close();
        });
        pools.clear();
    }

    public Map<String, Connection> getConnections() {
        return pools;
    }
}
